<template>
  <div class="app-container planList">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="内容" prop="dos">
        <el-input
          v-model="queryParams.dos"
          placeholder="请输入计划内容"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="责任人" prop="uploader">
        <el-input
          v-model="queryParams.uploader"
          placeholder="请输入责任人"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="部门" prop="uploadDept">
        <el-input
          v-model="queryParams.uploadDept"
          placeholder="请输入所属部门"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="日期">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="!todayFinished"
          v-hasPermi="['plan:planList:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>

        <el-button
          v-else
          disabled
          type="primary"
          plain
          icon="el-icon-circle-check"
          size="mini"
        >已填写</el-button>
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['plan:planList:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->

      <el-col :span="1.5">
        <el-button
          v-hasPermi="['plan:planList:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          v-hasPermi="['plan:planList:countDept']"
          type="info"
          plain
          icon="el-icon-info"
          size="mini"
          @click="count('dept')"
        >部门统计</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          v-hasPermi="['plan:planList:countCompany']"
          type="info"
          plain
          icon="el-icon-s-data"
          size="mini"
          @click="count('company')"
        >公司统计</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="planList"
      row-key="id"
      border
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="计划内容" prop="dos" align="left" header-align="center" show-overflow-tooltip min-width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.children" class="planName" @click="handleUpdate(scope.row, false)">{{ scope.row.dos }}</span>
          <span v-else>{{ scope.row.dos }}</span>
        </template>
      </el-table-column>

      <el-table-column label="责任人" prop="uploader" align="center" min-width="100" show-overflow-tooltip />

      <el-table-column label="部门" prop="uploadDept" align="center" min-width="150" show-overflow-tooltip />

      <el-table-column label="关联任务" prop="dispathName" align="center" show-overflow-tooltip min-width="160" />

      <el-table-column label="日期" prop="uploadtime" align="center" min-width="120" show-overflow-tooltip />

      <el-table-column label="完成时间" prop="completeTime" align="center" min-width="120" show-overflow-tooltip />

      <el-table-column label="总结" prop="planSummary" align="center" show-overflow-tooltip min-width="200" />

      <el-table-column label="状态" prop="state" align="center" min-width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.state === '0'">未完成</span>
          <span v-else style="color: #13ce66;">已完成</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template v-if="scope.row.roleId !== 1" slot-scope="scope">
          <el-button
            v-if="scope.row.children && scope.row.uploadtime === getDateTime().ymd && scope.row.uploader === userInfo.nickName"
            v-hasPermi="['plan:planList:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, true)"
          >修改</el-button>
          <el-button
            v-if="scope.row.children"
            v-hasPermi="['plan:planList:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            v-if="!scope.row.children && !scope.row.planSummary && scope.row.state === '1'"
            v-hasPermi="['plan:planList:summary']"
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleSummary(scope.row)"
          >总结</el-button>
          <el-button
            v-if="!scope.row.children && scope.row.state === '0'"
            v-hasPermi="['plan:planList:finish']"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleFinish(scope.row)"
          >完成</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="100">
          <el-col :span="24">
            <el-form-item label="计划内容" prop="dos">
              <el-input
                v-model="form.dos"
                :disabled="!canEdit"
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 100}"
                placeholder="请输入计划内容"
              />
            </el-form-item>
          </el-col>

          <el-col v-for="(item, index) in form.children" :key="item.key" :span="24">
            <el-row :gutter="20">
              <el-col :span="20">
                <el-form-item
                  :label="(title === '添加计划' && item.planId) || (title === '修改计划' && item.hisPlanId) ? '历史子计划' : '子计划'"
                  :prop="'children.' + index + '.dos'"
                  :rules="{ required: true, message: '请填写详细条目', trigger: 'blur' }"
                >
                  <el-input
                    v-model="item.dos"
                    :disabled="!canEdit || (title === '添加计划' && item.planId) || (title === '修改计划' && item.hisPlanId)"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 100}"
                    placeholder="请输入计划内容"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="20">
                <el-form-item label="关联任务" prop="dispath">
                  <el-tooltip slot="label" class="item" effect="dark" content="选择该条目关联的任务" placement="top">
                    <i class="el-icon-info">关联任务</i>
                  </el-tooltip>

                  <el-select
                    v-model="item.dispath"
                    :disabled="!canEdit || (title === '添加计划' && item.planId) || (title === '修改计划' && item.hisPlanId)"
                    clearable
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请选择关联任务"
                    :remote-method="projectRemoteMethod"
                    :loading="taskLoading"
                    style="width: 100%;"
                  >
                    <el-option
                      v-for="val in taskOptions"
                      :key="val.value"
                      :label="val.label"
                      :value="val.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col v-if="canEdit" :span="3">
                <el-button icon="el-icon-plus" circle @click="addPlanItem(item, index)" />
                <el-button v-if="form.children.length > 0" icon="el-icon-minus" circle @click="deletePlanItem(item, index)" />
              </el-col>
            </el-row>
          </el-col>

          <el-col v-if="!canEdit" :span="24">
            <el-form-item label="总结" prop="dones">
              <el-input
                v-model="form.dones"
                disabled
                type="textarea"
                :rows="5"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="!canEdit" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openUserStatusTable" width="600px">
      <p>
        <el-button type="primary" plain @click="filterUser()">全部：{{ sumNumber }}</el-button>
        <el-button type="success" plain @click="filterUser('0')">已上传：{{ yesNumber }}</el-button>
        <el-button type="danger" plain @click="filterUser('1')">未上传：{{ noNumber }}</el-button>
      </p>
      <el-table :data="userStatusList" max-height="650">
        <el-table-column property="uploader" label="姓名" width="150" />
        <el-table-column property="uploadDept" label="部门" width="200" />
        <el-table-column property="state" label="状态" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.state === '0' ? '已上传' : '未上传' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listPlan, getPlanDetail, deletePlan, addPlan, updatePlan, getTodayPlan, getTodayAllPlan, updateItemState, historylist, summaryPlan } from '@/api/plan/planList'
import { listTask } from '@/api/work/task'

export default {
  name: 'Plan',

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选择关联任务
      taskLoading: false,
      // 关联任务列表
      taskOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 当天计划是否已填写
      todayFinished: false,
      // 总条数
      total: 0,
      // 表格数据
      planList: [],
      // 上传统计数据
      userStatusList: [],
      sumNumber: null,
      yesNumber: null,
      noNumber: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 能否编辑
      canEdit: true,
      // 是否显示统计弹出层
      openUserStatusTable: false,
      // 日期范围
      dateRange: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {
        dos: '',
        children: [
          {
            key: new Date().getTime(),
            dos: '',
            dispath: ''
          }
        ]
      },
      // 表单校验
      rules: {
        dos: [
          { required: true, message: '请填写今日计划', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    }
  },

  created() {
    this.getList()
  },

  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        startTime: this.dateRange && this.dateRange[0],
        endTime: this.dateRange && this.dateRange[1]
      }
      console.log('查询列表参数', params)
      listPlan(params).then(response => {
        this.planList = response.rows
        this.total = response.total
        this.loading = false
      })

      // 判断当天计划是否已填写
      listPlan({
        startTime: this.getDateTime().ymd,
        endTime: this.getDateTime().ymd
      }).then(response => {
        this.todayFinished = response.rows.length > 0
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        dos: undefined,
        children: [
          {
            key: new Date().getTime() + '',
            dos: '',
            dispath: ''
          }
        ]
      }
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = null
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection // .map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.canEdit = true
      this.open = true
      this.title = '添加计划'
      historylist().then(res => {
        console.log('历史未完成条目', res)
        this.form.children = res.data.length > 0 ? res.data : this.form.children
      })
    },

    /** 修改 & 详情按钮操作 */
    handleUpdate(row, canEdit) {
      this.reset()
      getPlanDetail(row.id).then(response => {
        this.form = response.data
        this.taskOptions = response.data.children.filter(value => {
          return !!value.dispathName
        }).map(val => {
          return {
            label: val.dispathName,
            value: val.dispath
          }
        })
        this.open = true
        this.canEdit = !!canEdit
        this.title = canEdit ? '修改计划' : '详情'
      })
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title === '修改计划') {
            const params = {
              ...this.form
            }
            console.log('修改params', params)
            updatePlan(params).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            const params = {
              ...this.form
            }
            console.log('新增params', params)
            addPlan(params).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    // 条目完成
    handleFinish(row) {
      this.$modal.confirm('是否确认完成？').then(function() {
        return updateItemState(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(() => {})
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids.map(item => item.id)
      const msg = row.planDate || this.ids.map(item => item.planDate)
      this.$modal.confirm('是否确认删除日期为"' + msg + '"的日程计划？').then(function() {
        return deletePlan(roleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },

    // 总结
    handleSummary(row) {
      this.$prompt('请输入计划总结', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        closeOnClickModal: false,
        inputValidator: (value) => {
          if (!value) {
            return '计划总结不能为空！'
          }
        }
      }).then(({ value }) => {
        summaryPlan({
          id: row.id,
          planSummary: value
        }).then(response => {
          this.$modal.msgSuccess('填写成功')
          this.getList()
        })
      }).catch()
    },

    // 计划上传情况统计
    count(str) {
      if (str === 'dept') {
        getTodayPlan().then(res => {
          console.log('部门统计', res)
          this.userStatusList = res.data
          this.sumNumber = res.data.length
          this.noNumber = res.data.filter(val => { return val.state === '1' }).length
          this.yesNumber = res.data.filter(val => { return val.state === '0' }).length
          this.title = '部门日程计划统计'
          this.openUserStatusTable = true
        })
      } else {
        getTodayAllPlan().then(res => {
          console.log('公司统计', res)
          this.userStatusList = res.data
          this.sumNumber = res.data.length
          this.noNumber = res.data.filter(val => { return val.state === '1' }).length
          this.yesNumber = res.data.filter(val => { return val.state === '0' }).length
          this.title = '公司日程计划统计'
          this.openUserStatusTable = true
        })
      }
    },

    // 计划上传情况统计筛选
    filterUser(state) {
      if (this.title === '部门日程计划统计') {
        getTodayPlan().then(res => {
          console.log('部门统计', res)
          this.userStatusList = res.data.filter(val => {
            return state ? val.state === state : true
          })
        })
      } else {
        getTodayAllPlan().then(res => {
          console.log('公司统计', res)
          this.userStatusList = res.data = res.data.filter(val => {
            return state ? val.state === state : true
          })
        })
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/plan/export', {
        ...this.queryParams
      }, `日程计划_${new Date().getTime()}.xlsx`, 'get', 'local')
    },

    // 远程搜索关联任务
    projectRemoteMethod(query) {
      console.log('远程搜索关联任务', query)
      if (query) {
        this.taskLoading = true
        listTask({ title: query }).then(res => {
          this.taskOptions = res.rows.map(val => {
            return {
              label: val.title,
              value: val.id
            }
          })
          this.taskLoading = false
        })
      } else {
        this.taskOptions = []
      }
    },

    addPlanItem(item, index) {
      this.form.children.splice(index + 1, 0, {
        key: new Date().getTime() + '',
        dos: ''
      })
    },

    deletePlanItem(item, index) {
      this.form.children.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.planList {
  .planName{
    color: #1890ff;
    cursor: pointer;

    &:hover{
      color: #1682e6;
    }
  }
}
</style>
